For my React App, all I want to do is take the current functionality of Tab and Shift Tab, but have the Up/Down arrows do same thing.
I know you can kind of emulate this behavior with Reacts "useRef" and "focus", but my App will have dynamically rendered elements that are always changing.
I am working with a Recursive Component which populates a Recursive Tree based on users input. I also plan to allow the child node order to be sortable (by multiple fields and sorting order).
So there is no (easy) way to know which "ref" the prev/next element would be. This makes "ref.current.focus()" pretty much unusable.
But once the Dom is rendered, the Tab and Shift Tab work exactly like I want...
... I just want to have the Up/Down arrow keys do this instead (i.e. the Up-Arrow would do the Shift Tab action and Down-Arrow would do the Tab action).
Is there anyway to programmatically send a Tab/Shift Tab keystroke in a React App?
Or maybe somehow change focus to the previous/next "sibling" after the DOM is built (i.e. ref.current.nextSibling.focus())?
I can't seem to get any of these approaches to work.
you can listen to the keypress in componentDidMount()
componentDidMount(){
document.addEventListener("keydown", this.handleKeyDown);
}
And your handleKeyDown will be;
handleKeyDown(e) {
e.preventDefault();
if(e.keyCode == 38){
//up arrow
e.dispatchEvent(new Event('keypress', {keyCode: 9}))
}
}